package cn.bluethink.timescaledb.mapper;

import onegis.psde.dynamicdata.DynamicData;
import onegis.psde.dynamicdata.ObjectDynamicData;
import onegis.psde.dynamicdata.ObjectDynamicDatas;
import onegis.psde.psdm.Location;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 实现必须实现此方法以映射ResultSet中的每一行数据。此方法不应调用next()ResultSet; 它只应映射当前行的值。
 * 参数：
 * rs - 要映射的ResultSet（为当前行预先初始化）
 * rowNum - 当前行的编号
 * 返回：
 * 当前行的结果对象
 * SQLException - 如果遇到SQLException获取列值（也就是说，不需要捕获SQLException）
 * https://docs.spring.io/spring/docs/2.0.8/javadoc-api/org/springframework/jdbc/core/RowMapper.html
 */
public class TimeScaleDynamicRowMapper implements RowMapper {

    private List<String> columns;

    @Override
    public ObjectDynamicDatas mapRow(ResultSet resultSet, int i) throws SQLException {
        ObjectDynamicDatas objectDynamicDatas = new ObjectDynamicDatas();
        List<ObjectDynamicData> objectDynamicDataList = new ArrayList<>();
        ObjectDynamicData objectDynamicData = new ObjectDynamicData();
        objectDynamicData.setStartTime(resultSet.getTime("startTime"));
        objectDynamicData.setEndTime(resultSet.getTime("endTime"));
        objectDynamicData.setOid(resultSet.getLong("oid"));
        List<DynamicData> dynamicDataList = new ArrayList<>();
        DynamicData dynamicData = new DynamicData();
        dynamicData.setCurrentTime(resultSet.getTime("currentTime"));
        Location location = new Location();
        location.setZ(resultSet.getDouble("x"));
        location.setY(resultSet.getDouble("y"));
        location.setZ(resultSet.getDouble("z"));
        dynamicData.setLocation(location);
        List<DynamicData.Attribute> attributes = new ArrayList<>();
        for (String column : columns){
            DynamicData.Attribute attribute = new DynamicData.Attribute();
            attribute.setName(column);
            attribute.setValue(resultSet.getObject(column));
            attributes.add(attribute);
        }
        dynamicData.setAttributes(attributes);
        dynamicDataList.add(dynamicData);
        objectDynamicData.setDynamicData(dynamicDataList);
        objectDynamicDataList.add(objectDynamicData);
        objectDynamicDatas.setObjectDynamicDataList(objectDynamicDataList);
        return objectDynamicDatas;
    }

    public TimeScaleDynamicRowMapper(List<String> columns){
        this.columns = columns;
    }

}
